package com.yz.design.responsibilityDegin;

import org.springframework.beans.BeanUtils;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public final class ResponsibilityFactory {

    public static AbstractMessageResponsibility<Message> aResponsibility() {
        return new AResponsibility();
    }

    public static AbstractMessageResponsibility<Message> bResponsibility() {
        return new BResponsibility();
    }

    public static AbstractMessageResponsibility<Message> cResponsibility() {
        return new CResponsibility();
    }

    /**
     * 责任链模式
     */
    @SafeVarargs
    public static <T> AbstractMessageResponsibility<T> getHandlerResponsibilityChain(Class<? extends AbstractMessageResponsibility<T>>... handlers) {

        List<Object> list = Arrays.stream(handlers).map(BeanUtils::instantiateClass).collect(Collectors.toList());
        AbstractMessageResponsibility<T> result = null;
        for (int i = 1; i < list.size(); i++) {
            AbstractMessageResponsibility<T> pre = (AbstractMessageResponsibility<T>) list.get(i - 1);
            AbstractMessageResponsibility<T> cur = (AbstractMessageResponsibility<T>) list.get(i);
            cur.setNextHandler(pre);
            result = cur;
        }
        return result;
    }
}